# -*- coding: utf-8 -*-

import wsgiref.handlers
import xmw
from xmw.db import ds
from xmw.db import counter
from google.appengine.ext import webapp
from google.appengine.ext import db
import urllib
from xmw import error
import datetime
import logging
from xmw.db import user_mgr
import xmlrpclib
import global_setting
from xmw.db.mail import *
from google.appengine.api import mail
class MainPage(xmw.RequestHandler):
    limit=7
    mailed_cnt=0
    
    def do(self):
        cnt=0
        task_q    =MailTask().all()
        task_q.filter('is_finished =', False)
        task_q.order('seq')
        task= task_q.get()
        
        if task is None:
            logging.info("No Mail Task Found!")
            return cnt
        
        seq=task.seq
        mr_q=MailRecord.all()
        mr_q.filter('seq =',seq)
        mr =mr_q.get()
        if mr is None:
            mr=MailRecord()
            mr.seq=seq
            mr.subject=task.subject
            mr.save()
        
        #looking for the recepts not send
        message = mail.EmailMessage(sender=u"""西门外<ximenwai.liu@gmail.com>""")
        message.subject = task.subject
        message.html=task.content
        message.reply_to='string@xmw-rec-mail.appspotmail.com'
        
        is_breaked=False
        for recept in task.lst_recepts:
            if mr.find_recepts(recept):
                #already send
                continue
            else:
                #send mail
                message.to=recept
                logging.info("ready to send mail:\n recept:%s\n subject:%s\n seq:%d\n"%(str(recept),
                                                                             message.subject,
                                                                             seq))
                message.send()
                cnt=cnt+1
                self.mailed_cnt=self.mailed_cnt+1
                
                mr.lst_recepts.append(recept)
                mr.save()
                if self.mailed_cnt >= self.limit:
                    is_breaked=True
                    break
                
        #now all finished when it comes here
        if not is_breaked:
            task.is_finished=True  
            task.put()
        return cnt
    
    def get(self):
        a=datetime.datetime.now()
        cnt=self.do()
        logging.info('send mail count:%d'%(cnt))
        
        while self.mailed_cnt< self.limit:
            b=datetime.datetime.now()
            c=b-a
            if c.seconds <1:
                if cnt == 0:
                    break
                cnt=self.do()
                logging.info('send mail count:%d'%(cnt))
                
                
            else:
                break
            
            
                    
        logging.info('\n mail sent count:%d,time cost: %s \n '%(self.mailed_cnt,str(c)))
        
        
                    
    
        
def main():
  application = webapp.WSGIApplication(
                                       [('/robot/sendmail', MainPage)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)

if __name__ == "__main__":
  main()